"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createLoopTakManager = void 0;
/*

    class TestTask {
        dispatcher(task: LoopTaskManager) {
            console.log('test');
        }
    }


    const ttTask = new TestTask();
    const ccTask2 = new LoopTaskManager(ttTask);
    const ccTask1 = new LoopTaskManager(async (task: any) => {
        console.log('test');
    });

 */
class LoopTaskManager {
    constructor(dispatcher, options = {}) {
        this.dispatcher = dispatcher;
        this.options = options;
        this.busy = false;
        this.timer = -1;
        this.destroyed = false;
        this.key = Math.random();
        this.next = this.next.bind(this);
        this.asyncNext = this.asyncNext.bind(this);
        this.forceNext = this.forceNext.bind(this);
    }
    idle() {
        this.busy = false;
    }
    forceNext() {
        this.idle();
        this.next();
    }
    next() {
        if (this.destroyed)
            return;
        if (this.busy)
            return;
        this.busy = true;
        const context = this.dispatcher;
        const dispatcher = (context === null || context === void 0 ? void 0 : context.dispatcher) || context;
        Promise.resolve(dispatcher.call(context, this)).catch((err) => {
            this.asyncNext();
            return Promise.reject(err);
        });
    }
    asyncNext(inter) {
        var _a;
        clearTimeout(this.timer);
        this.timer = setTimeout(this.next, inter || ((_a = this.options) === null || _a === void 0 ? void 0 : _a.inter) || 1e3);
    }
    destroy() {
        this.destroyed = true;
        clearTimeout(this.timer);
        console.log('[destroy loop task]', this.key);
    }
}
function createLoopTakManager(dispatcher, options) {
    return new LoopTaskManager(dispatcher, options);
}
exports.createLoopTakManager = createLoopTakManager;
